package main

import (
	"github.com/gin-gonic/gin"
)

type User struct {
	//校验标签,可以查看: github.com/go-playground/validator
	//id 必须(required), uuid类型(uuid)
	ID string `form:"id" binding:"required,uuid"`
}

type Person struct {
	// json 格式的校验
	ID string `json:"id" binding:"required"`
	//注意: 这里的逗号(,)后面不要接空格等字符
	Name string `json:"name" binding:"required,min=3,max=8"`
}

func main() {

	r := gin.Default()

	// 参数校验(should)
	// http://localhost:8080/user?id=123456
	// http://localhost:8080/user?id=ed7d5477-247f-475e-97a6-92ff70cc2839
	r.GET("/user", func(c *gin.Context) {
		var user User
		// ShouldBindQuery 绑定失败报 200
		if err := c.ShouldBindQuery(&user); err != nil {
			c.JSON(200, gin.H{
				"code": 500,
				"id":   err.Error(),
			})
		} else {
			c.JSON(200, gin.H{
				"code": 200,
				"msg":  user.ID,
			})
		}
	})

	// 参数校验(must)
	// http://localhost:8080/user2?id=123456
	// http://localhost:8080/user2?id=ed7d5477-247f-475e-97a6-92ff70cc2839
	r.GET("/user2", func(c *gin.Context) {
		var user User
		// BindQuery 绑定失败报 400
		if err := c.BindQuery(&user); err != nil {
			c.JSON(200, gin.H{
				"success": false,
				"id":      err.Error(),
			})
			return
		}
		c.JSON(200, gin.H{
			"success": true,
			"msg":     user.ID,
		})

	})

	//uri携带参数, form也携带参数
	// http://localhost:8080/person
	/*
		{
		    "id":"123@163.com",
		    "name":"soul_gin"
		}
	*/
	r.POST("/person", func(c *gin.Context) {
		var person Person
		if err := c.ShouldBindJSON(&person); err != nil {
			c.JSON(200, gin.H{
				"success": false,
				"id":      err.Error(),
			})
			return
		}
		c.JSON(200, gin.H{
			"success": true,
			"ID":      person.ID,
			"Name":    person.Name,
		})

	})

	r.Run()
}
